import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fromJS } from 'immutable'

import Loading from '../../../component/loading/Loading'

import { intl } from '../../../intl/intl'
import { formatContractPriceDecimal, formatDecimal, formatValue } from '../../../utils/dataUtils'

import { pollPosition, setPollPositionEnabled } from '../../../redux/actions/tradeDataQueryAction'

@connect((state) => {
  return {
    contracts: state.trade.market.get('contracts'),
    currentContract: state.trade.market.get('currentContract'),
    positionLoading: state.trade.dataQuery.get('positionLoading'),
    positionList: state.trade.dataQuery.get('positionList'),
    showDealDetail: state.trade.dealDetail.get('showDealDetail')
  }
}, (dispatch) => {
  return bindActionCreators({
    pollPosition
  }, dispatch)
})
class Position extends Component {
  componentDidMount () {
    this.props.pollPosition()
  }

  componentWillUnmount () {
    setPollPositionEnabled(false)
  }

  renderLoading () {
    if (this.props.positionLoading) {
      return <Loading className="trade-data-query-table-loading"/>
    }
  }

  renderEmpty (dataList) {
    const { positionLoading } = this.props
    if (!positionLoading && dataList.size === 0) {
      return <p className="trade-data-query-table-no-data">{intl('no_data')}</p>
    }
  }

  renderTableContent (dataList) {
    const { showDealDetail } = this.props
    const close = formatValue(showDealDetail.get(0), 'Price', 1)
    return dataList.map(position => {
      const id = formatValue(position, 'InstrumentID')
      const contract = formatValue(this.props.contracts, id, fromJS({}))
      const isInverse = formatValue(contract, 'IsInverse', 0)
      const volumeMultiple = formatValue(contract, 'VolumeMultiple', 1)
      const direction = formatValue(position, 'PosiDirection')
      const positionCost = formatValue(position, 'PositionCost', 0)
      const volume = formatValue(position, 'Position', 0)
      const longFrozenVolume = formatValue(position, 'LongFrozen', 0)
      const shortFrozenVolume = formatValue(position, 'ShortFrozen', 0)
      let buySell = ''
      let closeVolume
      if (direction === 48) {
        closeVolume = volume - shortFrozenVolume
        if (volume < 0) {
          buySell = 'sell'
        } else {
          buySell = 'buy'
        }
      } else if (direction === 49) {
        buySell = 'sell'
        closeVolume = volume - longFrozenVolume
      } else {
        closeVolume = volume - shortFrozenVolume
        buySell = 'sell'
      }
      const averagePrice = isInverse ? volume * volumeMultiple / positionCost : positionCost / volumeMultiple / volume
      let unrealizedProfitLoss
      if (direction === 48) {
        if (isInverse) {
          unrealizedProfitLoss = closeVolume * volumeMultiple / averagePrice - closeVolume * volumeMultiple / close
        } else {
          unrealizedProfitLoss = close / closeVolume * volumeMultiple - averagePrice / closeVolume * volumeMultiple
        }
      } else {
        if (isInverse) {
          unrealizedProfitLoss = closeVolume * volumeMultiple / close - closeVolume * volumeMultiple / averagePrice
        } else {
          unrealizedProfitLoss = averagePrice / closeVolume * volumeMultiple - close / closeVolume * volumeMultiple
        }
      }
      return (
        <tr key={`${id}_${direction}`}>
          <td>{id}</td>
          <td
            datatype={buySell}>{intl(buySell)}</td>
          <td>{volume === 0 ? '--' : formatContractPriceDecimal(contract, averagePrice)}</td>
          <td>{formatDecimal(formatValue(position, 'UseMargin'), 8)}</td>
          <td>{formatDecimal(formatValue(position, 'FrozenMargin'), 8)}</td>
          <td>{formatDecimal(unrealizedProfitLoss, 8)}</td>
          <td>{formatDecimal(formatValue(position, 'CloseProfit'), 8)}</td>
          <td>{formatValue(position, 'Position').toFixed(0)}</td>
          <td>{(closeVolume).toFixed(0)}</td>
        </tr>
      )
    })
  }

  render () {
    const { positionList, currentContract, type } = this.props
    const dataList = type
      ? positionList.filter(position => formatValue(position, 'InstrumentID') === formatValue(currentContract, 'InstrumentID') && formatValue(position, 'Position', 0) !== 0)
      : positionList.filter(position => formatValue(position, 'Position', 0) !== 0)
    return (
      <div className="trade-data-query-table-container">
        <table>
          <thead>
            <tr>
              <td>{intl('name')}</td>
              <td>{intl('direction')}</td>
              <td>{intl('open_position_average_price')}</td>
              <td>{intl('position_margin')}</td>
              <td>{intl('frozen_margin')}</td>
              <td>{intl('unrealized_profit_loss')}</td>
              <td>{intl('income')}</td>
              <td>{intl('position_volume')}</td>
              <td>{intl('can_close_position_volume')}</td>
            </tr>
          </thead>
          <tbody>
            {this.renderTableContent(dataList)}
          </tbody>
        </table>
        {this.renderLoading()}
        {this.renderEmpty(dataList)}
      </div>
    )
  }
}

export default Position
